<template>
  <el-pagination
    class="pagination"
    @current-change="handleCurrentChange"
    :current-page="listQuery.pageNum"
    :page-sizes="[]"
    :page-size="listQuery.pageSize"
    layout="prev, pager, next, slot, jumper, total"
    :total="listQuery.total">
    <span class="pageSizeInput">
      <el-input
        class="pageSizeBorder"
        v-model.number="pageSize"
        @input="handlePageSize"
        @blur="setPageSize"
        @keyup.enter.native="setPageSize"
        onafterpaste="if(this.pageSize.length==1){this.pageSize=this.pageSize.replace(/[^1-9]/g,'')}else{this.pageSize=this.pageSize.replace(/\D/g,'')}"
      ></el-input> 条/页
    </span>
  </el-pagination>
</template>

<script>
export default {
  name: 'Pagination',
  props:{
    listQuery: {
      type: Object,
      default: () => {
        return {
          total: 0,
          pageNum: 1,
          pageSize: 10,
        }
      }
    }
  },
  data(){
    return {
      pageSize: this.listQuery.pageSize
    }
  },
  methods:{
    // 翻页
    handleCurrentChange(currentPage) {
      this.$emit('page-change', { currentPage, pageSize:  this.pageSize})
    },

    // 自定义每页显示条数
    setPageSize ({ target: { value } }) {
      if (Number(value) !== this.listQuery.pageSize) {
        if (this.pageSize > 1000) {
          this.pageSize = 1000
          this.$message.warning('每页最多显示1000条')
        }
        this.$emit('page-change', { currentPage: 1, pageSize:  this.pageSize})
      }
    },

    // 监听pageSize文本框的变化，处理不合法数据格式
    handlePageSize (val) {
      if(this.pageSize.length == 1){
        this.pageSize = Number(String(this.pageSize).replace(/[^1-9]/g, ''))
      }else{
        this.pageSize = Number(String(this.pageSize).replace(/\D/g, ''))
      }
      if (Number(this.pageSize) === 0 ) {
        this.pageSize = 1
      }
    }
  },
}
</script>
<style lang="scss" scoped>
  .pagination {
    float: right;
    margin-top: 10px;
    ::v-deep .el-pagination__jump {
      margin-left: 0;
      margin-right: 10px;
    }
  }
  .pageSizeInput {
    height: 28px;
    line-height: 28px;
    margin: 0 10px;
    font-weight: 500;
    ::v-deep .el-input {
      width: 50px;
      text-align: center;
    }
    ::v-deep .el-input__inner {
      height: 28px;
      line-height: 28px;
      padding: 0;
    }
  }
</style>
